<!--  商品列表-->
<template>
  <div class="category-list">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/admin/main' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item
        ><a href="javascript:;">产品管理</a></el-breadcrumb-item
      >
      <el-breadcrumb-item>产品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="handlerAdd">添加分类</el-button>
      <el-table
        :data="tableData.data"
        style="width: 100%; margin-bottom: 20px"
        row-key="cid"
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="cid" label="商品序号"> </el-table-column>
        <el-table-column prop="title" label="商品标题"> </el-table-column>
        <el-table-column label="商品图片" prop="imgsrc">
          <template slot-scope="scope">
            <el-avatar
              shape="square"
              size="large"
              :src="Setting.baseUrl + scope.row.imgsrc"
            ></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="是否可用" prop="is_show">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_show"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
              active-text="可用"
              inactive-text="禁用"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot="header"> 操作 </template>
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 15, 25, 35]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.count"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类弹框 -->
    <el-dialog title="添加分类" :visible.sync="dialogVisibleAdd" width="30%">
      <el-form
        id="of"
        status-icon
        label-width="80px"
        ref="ruleForm"
        :model="productData"
        :rules="rules"
      >
        <el-form-item label="分类">
          <el-cascader
            v-model="value"
            :options="options"
            :props="{ checkStrictly: true }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="productData.title"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            :action="Setting.apiBaseUrl+'/admin/uploadimg'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="Setting.baseUrl + imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否可见" prop="is_show">
          <el-switch
            v-model="productData.is_show"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="可用"
            inactive-text="禁用"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="goAddCate('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改" :visible.sync="dialogVisibleEdit" width="30%">
      <el-form
        id="of"
        status-icon
        label-width="80px"
        ref="ruleForm"
        :model="editData"
        :rules="rules"
      >
        <el-form-item label="分类">
          <el-cascader
            v-model="value2"
            :options="options"
            :props="{ checkStrictly: true }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="editData.title"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            :action="Setting.apiBaseUrl+'/admin/uploadimg'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess1"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl1"
              :src="Setting.baseUrl + imageUrl1"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否可见" prop="is_show">
          <el-switch
            v-model="editData.is_show"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="可用"
            inactive-text="禁用"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="goEditCate('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 删除模态框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>你确定要删除此商品吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deletePro">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { addCategory, editCategory, delCategory } from "@/api/category";
import Setting from "@/utils/setting.js"

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var checkTitle = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("标题不能为空"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      Setting:Setting,
      value: [],
      value2: [],
      dialogVisible: false,
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      /* tableData: [
        {
          cid: 1,
          title: "大家电",
          is_show: "1",
          imgsrc: "",
          children: [
            {
              cid: 11,
              title: "冰箱",
              imgsrc: "",
              is_show: "1",
            },
            {
              cid: 12,
              title: "空调",
              imgsrc: "",
              is_show: "1",
            },
          ],
        },
        {
          cid: 2,
          title: "厨房电器",
          is_show: "1",
          imgsrc: "",
          children: [
            {
              cid: 21,
              title: "电饭煲",
              imgsrc: "",
              is_show: "0",
            },
            {
              cid: 22,
              title: "电饼铛",
              imgsrc: "",
              is_show: "1",
            },
          ],
        },
      ], */
      productData: {
        title: "",
        is_show: "1",
        imgsrc: "",
      },
      editData: {
        title: "",
        is_show: "",
        imgsrc: "",
      },
      productDel: {},
      rules: {
        title: [{ validator: checkTitle, trigger: "blur" }],
      },
      page: 1,
      size: 5,
      imageUrl: "",
      imageUrl1: "",
      value1: "",
    };
  },
  //监听属性 类似于data概念
  computed: {
    options() {
      return this.$store.state.category.categoryaddlist;
    },
    tableData() {
      return this.$store.state.category.categorylist;
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    handleClick(tab) {
      console.log(tab);
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogVisibleEdit = true;
      this.editData = row;
      this.imageUrl1 = row.imgsrc;
    },
    handleDelete(index, row) {
      // console.log(index, row);
      this.dialogVisible = true;
      this.productDel = row;
    },
    handleAvatarSuccess(res) {
      this.imageUrl = res.data.path;
    },
    handleAvatarSuccess1(res) {
      this.imageUrl1 = res.data.path;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //添加分类
    goAddCate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$set(this.productData, "imgsrc", this.imageUrl);
          this.$set(this.productData, "value", this.value);
          addCategory(this.productData).then((res) => {
            // console.log(res.data);
            if (res.data.status == 200) {
              this.$refs["ruleForm"].resetFields();
              this.value = [];
              this.imageUrl = "";
              this.dialogVisibleAdd = false;
              this.$message({
                message: res.data.msg,
                type: "success",
              });
              this.getcategoryData();
              this.getcategorylist();
            } else if (res.data.status == 1001) {
              this.$message({
                message: res.data.msg,
                type: "warning",
              });
            } else {
              this.$message({
                message: res.data.msg,
                type: "warning",
              });
            }
          });
        }
      });
    },
    // 修改
    goEditCate(formName) {
      console.log(formName);
      this.$set(this.editData, "imgsrc", this.imageUrl1);
      this.$set(this.editData, "value", this.value2);
      editCategory(this.editData).then((res) => {
        console.log(res.data);
        if (res.data.status == 200) {
          this.$message({
            message: res.data.msg,
            type: "success",
          });
          this.$refs["ruleForm"].resetFields();
          this.value2 = [];
          this.imageUrl1 = "";
          this.dialogVisibleEdit = false;
          this.getcategoryData();
          this.getcategorylist();
        } else {
          this.$message({
            message: res.data.msg,
            type: "warning",
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      // console.log(this.$refs[formName]);
    },
    // 删除
    deletePro() {
      delCategory(this.productDel).then((res) => {
        // console.log(res);
        if (res.data.status == 200) {
          this.$message({
            message: res.data.msg,
            type: "success",
          });
          this.getcategoryData();
          this.getcategorylist();
          this.dialogVisible = false;
        } else if (res.data.status == 1001) {
          this.$message({
            message: res.data.msg,
            type: "warning",
          });
        } else {
          this.$message({
            message: res.data.msg,
            type: "warning",
          });
        }
      });
    },
    handleSizeChange(val) {
      this.page = 1;
      // console.log(`每页 ${val} 条`);
      this.size = val;
      this.getcategorylist();
    },
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`);
      this.page = val;
      this.getcategorylist();
    },
    handlerAdd() {
      this.dialogVisibleAdd = true;
    },
    handleChange(value) {
      console.log(value);
    },
    getcategoryData() {
      this.$store.dispatch("actchangeCategoryaddlist");
    },
    getcategorylist() {
      this.$store.dispatch("actchangeCategorylist", {
        page: this.page,
        size: this.size,
      });
    },
  },
  mounted() {
    this.getcategoryData();
    this.getcategorylist();
    // console.log(this.tableData);
    // console.log(this.$store.state.category);
  },
};
</script>
<style lang="less">
.category-list {
  .el-card {
    margin-top: 15px;
  }
}
</style>